<?php
/**
 * Created by PhpStorm.
 * User: 元曦
 * Date: 2023-02-22
 * Time: 16:46:19
 * Info: 模型管理
 */

namespace app\admin\controller;

use app\common\controller\AdminController;
use think\facade\View;
use app\common\model\ModelsField as ModelsFieldModel;
use app\common\model\Models as ConModels;
use app\common\model\ContentExt as ContentExtModel;
use app\common\model\ExtField as ExtFieldModel;

class ModelsField extends Base
{

    /**
     * 获取内容模型列表页
     * @return string
     */
    public function index()
    {
        $model_id = $this->request->param('model_id');
        $params   = [];
        //判断是否是ajax发送方式
        if ($this->request->isAjax()) {
            $params['limit'] = (int)input('limit', 10);
            $params['page']  = (int)input('page', 1);
            $params['first'] = ($params['page'] - 1) * $params['limit'];
            $params['field'] = input('field', 'id');
            $params['order'] = input('order', 'asc');
            $params['key']   = input('key');
            if ( ! empty($model_id)) {
                $params['key']['model_id'] = $model_id;
            }
            $data = ModelsFieldModel::getModelList($params);
            $this->success('ok', $data['list'], $data['count']);
        }
        View::assign('model_id', $model_id);

        return View::fetch();
    }

    /**
     * 添加内容模型
     * @return string
     * @throws \think\db\exception\DbException
     */
    public function add()
    {
        $contentExtModel = new ContentExtModel();

        if ($this->request->isPost()) {
            $param = $this->request->post();
            if (empty($param['model_id'])) {
                $this->error('请选择所属模型');
            }
            if (empty($param['name'])) {
                $this->error('字段名称不能为空');
            }
            if (empty($param['title'])) {
                $this->error('字段标题不能为空');
            }
            if (empty($param['type'])) {
                $this->error('字段类型不能为空');
            }

            if ($param['type'] == 3 || $param['type'] == 4 || $param['type'] == 7) {
                $valueNames  = array_filter($param['value']['name']);
                $valueValues = array_filter($param['value']['value']);
                if (empty($valueNames)) {
                    $this->error('请输入选项文字');
                }
                if (empty($valueValues)) {
                    $this->error('请输入选项值');
                }
                $newValue = [];
                foreach ($valueNames as $key => $n) {
                    if (empty($valueValues[$key])) {
                        $this->error('选项数据不完整');
                    }
                    array_push($newValue, ['name' => $n, 'value' => $valueValues[$key]]);
                }
                $param['value'] = json_encode($newValue, JSON_UNESCAPED_UNICODE);
            } elseif ($param['type'] == 9) {
                $param['value'] = $param['value2'];
            } else {
                $param['value'] = '';
            }
            unset($param['value2']);

            $param['name'] = "ext_".$param['name'];
            //查询文章额外字段表是否存在字段
            $isExistField = $contentExtModel->isExistField($param['name']);
            if (isset($isExistField['code']) && $isExistField['code'] == 0) {
                $this->error($isExistField['msg']);
            }
            if ($isExistField) {
                $this->error('字段已经存在，不能重复添加！');
            }

            // 字段类型及长度
            switch ($param['type']) {
                case '2': // 多行
                    $mysql = 'varchar(1000) NOT NULL';
                    break;
                case '6': // 多图
                    $mysql = 'varchar(1000) NOT NULL';
                    break;
                case '9': // 时间日期
                    $mysql = 'datetime';
                    break;
                case '10':
                case '11': // 编辑器
                    $mysql = 'LONGTEXT';
                    break;
                default:
                    $mysql = 'varchar(200) NOT NULL';
            }

            //在content_ext表中创建字段
            $contentExtModel->createField($param['name'], $param['type'], $mysql, $param['title']);
            //将创建的字段写入表：models_field
            ModelsFieldModel::create($param);
            $this->success('操作成功');
        }
        //模型下拉
        $model_id     = (int)input('get.model_id');
        $modelsIdList = ConModels::getModelsIdMenuList();
        $fieldType    = ModelsFieldModel::FORM_FIELDS;

        View::assign('model_id', $model_id);
        View::assign('modelsIdList', $modelsIdList);
        View::assign('field_type', $fieldType);

        return View::fetch();
    }

    /**
     * 修改内容模型
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit()
    {
        $contentExtModel = new ContentExtModel();
        if ($this->request->isPost()) {
            //获取序列化数据
            $param = $this->request->post();
            if (empty($param['id'])) {
                $this->error('参数错误');
            }
            if ($param['type'] == 3 || $param['type'] == 4) {
                $valueNames  = array_filter($param['value']['name']);
                $valueValues = array_filter($param['value']['value']);
                if (empty($valueNames)) {
                    $this->error('请输入选项文字');
                }
                if (empty($valueValues)) {
                    $this->error('请输入选项值');
                }
                $newValue = [];
                foreach ($valueNames as $key => $n) {
                    if (empty($valueValues[$key])) {
                        $this->error('选项数据不完整');
                    }
                    array_push($newValue, ['name' => $n, 'value' => $valueValues[$key]]);
                }
                $param['value'] = json_encode($newValue, JSON_UNESCAPED_UNICODE);
            } elseif ($param['type'] == 9) {

            } else {
                $param['value'] = '';
            }
            // 字段类型及长度
            switch ($param['type']) {
                case '2': // 多行
                    $mysql = 'varchar(1000)';
                    break;
                case '8': // 时间日期
                    $mysql = 'datetime';
                    break;
                case '9': // 编辑器
                    $mysql = 'LONGTEXT';
                    break;
                case '6': // 多图
                    $mysql = 'varchar(1000)';
                    break;
                default:
                    $mysql = 'varchar(200)';
            }
            //在content_ext表中更新字段
            $contentExtModel->updateField($param['name'], $mysql, $param['title']);
            //更新字段：models_field
            ModelsFieldModel::update($param, ['id' => $param['id']]);
            $this->success('操作成功');
        }
        $id   = input('get.id');
        $data = ModelsFieldModel::find($id);
        if (empty($data)) {
            $this->error('获取数据失败');
        }
        $data = is_object($data) ? $data->toArray() : $data;
        if ($data['type'] == 3 || $data['type'] == 4) {
            $data['value'] = json_decode($data['value'], true);
        }

        View::assign('data', $data);
        //模型下拉
        $model_id     = (int)input('get.model_id');
        $modelsIdList = ConModels::getModelsIdMenuList();
        $fieldType    = ModelsFieldModel::FORM_FIELDS;

        View::assign('model_id', $model_id);
        View::assign('modelsIdList', $modelsIdList);
        View::assign('field_type', $fieldType);

        return View::fetch();
    }

    /**
     * 修改内容模型
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function modify()
    {
        if ($this->request->isAjax()) {
            if (empty(input('get.id')) || empty(input('get.field'))) {
                $this->error('参数错误');
            }
            $param[input('get.field')] = input('val');
            $param['id']               = input('get.id');
            try {
                ModelsFieldModel::update($param, ['id' => $param['id']]);
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            $this->success('操作成功');
        }
    }

    /**
     * 删除内容模型
     * @return void
     */
    public function delete()
    {
        $contentExtModel = new ContentExtModel();
        if ($this->request->isAjax()) {
            $id = (int)input('get.id');
            if (empty($id)) {
                $this->error("参数错误");
            }
            $data = ModelsFieldModel::find($id);
            //在content_ext表中删除字段
            try {
                ModelsFieldModel::where(['id' => $id])->delete();
                $contentExtModel->deleteField($data['name']);
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            $this->success("删除成功");
        }
    }
}
